import { Repository, Like } from 'typeorm';
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';

import { LoginDTO } from './dto/login.dto';
import { WxUser } from './entities/wxuser.entity';
import { ApplyDoctorDto } from './dto/apply-doctor.dto';
import { Doctor } from '../doctor/entities/doctor.entity';

@Injectable()
export class WxUserService {
  constructor(
    @InjectRepository(WxUser)
    private readonly userRepository: Repository<WxUser>,
    @InjectRepository(Doctor)
    private readonly doctorRepository: Repository<Doctor>,
  ) {}

  async save(user: WxUser) {
    return await this.userRepository.save(user);
  }

  async getUserByPhone(phone: string) {
    return await this.userRepository.findOne({
      where: { phone: phone },
    });
  }

  async getUserById(id: number) {
    return await this.userRepository.findOne({
      where: { id: id },
    });
  }

  async updateUser(user: WxUser) {
    return await this.userRepository.update(user.id, user);
  }
  async findAll(): Promise<WxUser[]> {
    return this.userRepository.find();
  }
  async findCount() {
    return this.userRepository.count();
  }

  async getWxUserByList(query: any = {}) {
    const { page, size, username = '' } = query;
    const searchObj = {
      // 根据关键词模糊查询
      where: {
        username: Like(`%${username}%`),
      },
      // 根据分页信息查询
      skip: (page - 1) * size, // 从第x页开始，需要x条数据
      take: size,
    };

    const totalNum = {
      where: {
        username: Like(`%${username}%`),
      },
    };

    const data = await this.userRepository.find(searchObj);
    const total = await this.userRepository.count(totalNum);
    // 从数据库中获取结果，并作为响应返回
    return {
      data,
      total,
    };
  }
  async applyToBeDoctor(userId: number, applyDoctorDto: ApplyDoctorDto) {
    const user = await this.userRepository.findOne({
      where: { id: userId },
      relations: ['doctor'],
    });
    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    if (user.role === 1) {
      throw new Error('您已经是认证医师，无需再次申请');
    }

    const doctor = this.doctorRepository.create({
      ...applyDoctorDto,
      user,
      status: 'pending',
    });

    await this.doctorRepository.save(doctor);
    user.doctor = doctor;
    await this.userRepository.save(user);

    return { message: '申请提交成功，请等待审核' };
  }

  async approveDoctor(doctorId: number) {
    const doctor = await this.doctorRepository.findOne({
      where: { id: doctorId },
      relations: ['user'],
    });
    if (!doctor) {
      throw new NotFoundException('医生信息不存在');
    }

    doctor.status = 'approved';
    doctor.user.role = 1;
    await this.doctorRepository.save(doctor);
    await this.userRepository.save(doctor.user);

    return { message: '医生审核通过' };
  }

  async rejectDoctor(doctorId: number) {
    const doctor = await this.doctorRepository.findOne({
      where: { id: doctorId },
      relations: ['user'],
    });
    if (!doctor) {
      throw new NotFoundException('医生信息不存在');
    }

    doctor.status = 'rejected';
    await this.doctorRepository.save(doctor);

    return { message: '医生审核拒绝' };
  }
}
